package com.xiaozheng.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Package: com.xiaozheng.utils
 * @ClassName: ConnectionUtils
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/27 13:13
 * @What_is_this_file_for: 连接的工具栏
 * @Description: 用于从数据库中获取一个连接，并且实现线程的绑定
 */
public class ConnectionUtils {
    private ThreadLocal<Connection> tlobals = new ThreadLocal<Connection> ();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取当前线程上的连接
     * @return
     */
    public Connection getThreadConnection() {
        // 1.先从ThreadLocal上获取
        Connection conn = tlobals.get();
        //2.判断线程上是否有连接
        if (conn == null) {
            try {
                //3.从数据源中获取一个连接，并且和线程绑定，存入ThreadLocal中
                conn = dataSource.getConnection();
                tlobals.set(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //返回当前线程上的连接
        return conn;
    }

    /**
     * 把连接和线程解绑
     */
    public void removeConnection(){
        tlobals.remove();
    }
}
